var mysql = require("mysql");
var crypto = require('../utils/crypto');

var pool = null;

function nop(a,b,c,d,e,f,g){}
  
function query(sql,callback){  
    pool.getConnection(function(err,conn){  
        if(err){  
            callback(err,null,null);  
        }else{  
            conn.query(sql,function(qerr,vals,fields){  
                //释放连接  
                conn.release();  
                //事件驱动回调  
                callback(qerr,vals,fields);  
            });  
        }  
    });  
};

exports.init = function(config){
    pool = mysql.createPool({  
        host: config.HOST,
        user: config.USER,
        password: config.PSWD,
        database: config.DB,
        port: config.PORT,
    });
};

// 检查用户是否存在
exports.is_user_exist = function(username,salt,callback){
    callback = callback == null? nop:callback;
    if(username == null || salt == null){
        callback(false);
        return;
    }
    var sql = `SELECT * FROM z7_user WHERE  username = '${username}' AND salt = '${salt}'`;
    query(sql, function(err, rows, fields) {
        if (err) {
            throw err;
        }
        if(rows.length == 0){
            callback(false);
            return;
        }

        callback(true);
    });  
};

